package com.mar.bt.server.impl;

import java.io.InputStream;
import java.io.OutputStream;

import net.java.dev.marge.entity.ServerDevice;

import com.mar.bt.server.IBluetoothIOHandler;
/**
 * Ideally should be a pair for bluetooth Input and Output stream .
 * @author mar
 */
class BluetoothIOHandler implements IBluetoothIOHandler {
	
	private final OutputStream btOutputStream;
	private final InputStream btInputStream;
	private final ServerDevice btServerDevice; 
	
	BluetoothIOHandler( ServerDevice serverDevice ) {
		this.btServerDevice = serverDevice;
		this.btInputStream  = createInputStream(serverDevice);

        this.btOutputStream = createOutputStream();        
        // Start listening
        //TODO:  extract may be to a separate method
        this.btServerDevice.startListening();
        
	}

	protected OutputStream createOutputStream() {
		return new BTOutputStream(this.btServerDevice);
	}

	protected InputStream createInputStream(ServerDevice serverDevice) {
		BTInputStream btInputStream = new BTInputStream();
		serverDevice.setCommunicationListener(btInputStream);
		return btInputStream;
	}
	
	/* (non-Javadoc)
	 * @see com.mar.bt.server.IBluetoothIOHandler#getOutputStream()
	 */
	public OutputStream getOutputStream(){
		return btOutputStream;
	}
	
	/* (non-Javadoc)
	 * @see com.mar.bt.server.IBluetoothIOHandler#getInputStream()
	 */
	public InputStream getInputStream(){
		return btInputStream;
	}
	
	/* (non-Javadoc)
	 * @see com.mar.bt.server.IBluetoothIOHandler#close()
	 */
	public void close(){
		btServerDevice.stopListenning();
		btServerDevice.close();
	}
}
